package com.example.esdemo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.example.esdemo.entity.Book;
import com.example.esdemo.entity.ESBook;
import com.example.esdemo.mapper.BookMapper;
import com.example.esdemo.service.BookService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.esdemo.service.EsBookRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuyunbin
 * @since 2023-04-12
 */
@Service
@Slf4j
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {

    @Autowired
    private EsBookRepository esBookRepository;
    /**
     * 把数据加入到ES
     * @param books
     */
    @Override
    public void add2ES(List<Book> books) {
        //MySQL里面的存储方式和ES里面的存储方式是不一样的
        for (Book book : books) {
            //把Book转化成ESBook才能添加进ES
            ESBook esBook=new ESBook();
            //把book里面的属性拷贝到esBook
            esBook.setId(book.getId());
            esBook.setTitle(book.getTitle());
            esBook.setAuthor(book.getAuthor());
            esBook.setPrice(book.getPrice());
            //进行添加
            log.info("esBook:{}",esBook);
            //todo 添加到es
            esBookRepository.save(esBook);
        }

    }

    @Override
    public List<ESBook> findAll(String keyword) {
        //搜索title和author里面的keyword
        List<ESBook> list = esBookRepository.findByTitleOrAuthor(keyword, keyword);
        return list;
    }
}
